import * as Cesium from "cesium";

const TianMapOptions = {
    baseUrl: 'http://t0.tianditu.gov.cn/cia_w/wmts',
    format: 'image/jpeg',
    layer: 'img',
    style: 'default',
    tileMatrixSetID: 'w',
    tileMatrixLabels: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18'],
    tileWidth: 256,
    tileHeight: 256,
    tilingScheme: new Cesium.GeographicTilingScheme(),
    rectangle: Cesium.Rectangle.fromDegrees(-180, -90, 180, 90),
    minimumLevel: 0,
    maximumLevel: 18,
    tk: '',
    credit: '天地图',
};

class TianMapImageryProvider extends Cesium.UrlTemplateImageryProvider {

    constructor(options = {}) {
        // 合并默认值和传入的 options
        const providerOptions = { ...TianMapOptions, ...options };

        // 确保 options 包含必要属性
        if (!providerOptions.tilingScheme) {
            providerOptions.tilingScheme = new Cesium.GeographicTilingScheme();
        }
        if (!providerOptions.rectangle) {
            providerOptions.rectangle = Cesium.Rectangle.fromDegrees(-180, -90, 180, 90);
        }

        console.log(providerOptions);
        // 调用父类构造函数
        super(providerOptions);

        // 设置 ImageryProvider 的属性
        this.tilingScheme = providerOptions.tilingScheme;
        this.maximumLevel = providerOptions.maximumLevel;
        this.credit = new Cesium.Credit(providerOptions.credit);
        this.tileWidth = providerOptions.tileWidth;
        this.tileHeight = providerOptions.tileHeight;
        this.rectangle = providerOptions.rectangle;
        this.options = providerOptions; // 保存配置

        // 设置 ready 属性
        this.ready = true;
    }

    requestImage(x, y, level, request) {
        // 动态生成 URL
        const url = `${this.options.baseUrl}?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0` +
            `&LAYER=${this.options.layer}` +
            `&STYLE=${this.options.style}` +
            `&TILEMATRIXSET=${this.options.tileMatrixSetID}` +
            `&FORMAT=${this.options.format}` +
            `&TileMatrix=${this.options.tileMatrixLabels[level]}` +
            `&TileRow=${y}` +
            `&TileCol=${x}` +
            `&tk=${tk}`;

        // 加载图像
        return Cesium.ImageryProvider.loadImage(this, url);
    }
}

export {
    TianMapImageryProvider,
    TianMapOptions
};